//
//  AILoginController.m
//  HNBaseProject
//
//  Created by xujie on 2024/7/18.
//

#import "AILoginController.h"
#import "AIChargeListController.h"
#import "YNSHomeController.h"
#import "DCNavigationController.h"
#import "DCMyProductionViewController.h"
@interface AILoginController ()
{
    dispatch_source_t _timer;
}
@property (nonatomic, strong) UITextField *emailField;
@property (nonatomic, strong) UITextField *passField;
@property (nonatomic, strong) ExpandButton *choseBtn;//选择
@property (nonatomic, strong) UILabel *sendLab;
@property (nonatomic, strong) YYLabel *choseLab;//阅读
@property (nonatomic, strong) UILabel *loginLab;
@end

@implementation AILoginController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self createUI];
}

- (void)createUI {
    
    UIImageView *bgImageV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ai_home_bg"]];
    [self.view addSubview:bgImageV];
    bgImageV.frame = CGRectMake(0, 0, kScreenW, kScreenH);
    
    UILabel *welcomeLab = [[UILabel alloc] init];
    [self.view addSubview:welcomeLab];
    welcomeLab.textColor = [UIColor colorWithHexString:@"#204D7A"];
    welcomeLab.text = @"欢迎登录";
    welcomeLab.font = PFRFontSemibold(18);
    [welcomeLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.offset(kNavBarHeight+62);
    }];
    
    UIImageView *logoImageV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ai_login_logo"]];
    [self.view addSubview:logoImageV];
    [logoImageV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(welcomeLab.mas_bottom).offset(21);
    }];
    
    UIView *mailBg = [[UIView alloc] init];
    mailBg.layer.borderWidth = 1;
    mailBg.layer.borderColor = [UIColor dc_colorWithHexString:@"#FFFFFF" alpha:0.7].CGColor;
    mailBg.backgroundColor = [UIColor dc_colorWithHexString:@"#FFFFFF" alpha:0.4];
    mailBg.layer.cornerRadius = 23;
    mailBg.layer.masksToBounds = YES;
    [self.view addSubview:mailBg];
    [mailBg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(30);
        make.right.offset(-30);
        make.height.mas_equalTo(46);
        make.top.mas_equalTo(logoImageV.mas_bottom).offset(45);
    }];
    
    UIImageView *emailLogo = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ai_log_email"]];
    [mailBg addSubview:emailLogo];
    [emailLogo mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(17);
        make.top.offset(12);
        make.height.width.mas_equalTo(22);
    }];
    
    self.emailField = [[UITextField alloc] init];
    self.emailField.font = PFRFont(16);
    self.emailField.keyboardType = UIKeyboardTypeEmailAddress;
    self.emailField.textColor = [UIColor colorWithHexString:@"#000000"];
    NSString *placeHodle = @"填写邮箱";
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:placeHodle];
    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHexString:@"#AEBFCC"] range:NSMakeRange(0, placeHodle.length)];
    [attributedString addAttribute:NSFontAttributeName value:PFRFont(16) range:NSMakeRange(0, placeHodle.length)];
    self.emailField.attributedPlaceholder = attributedString;
    [mailBg addSubview:self.emailField];
    MJWeakSelf
    [self.emailField addBlockForControlEvents:UIControlEventEditingChanged block:^(UITextField *sender) {
        [weakSelf judgeBtnState];
    }];
    
    [self.emailField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(51);
        make.top.bottom.offset(0);
        make.right.offset(-5);
    }];
    
    UIView *passBg = [[UIView alloc] init];
    passBg.layer.borderWidth = 1;
    passBg.layer.borderColor = [UIColor dc_colorWithHexString:@"#FFFFFF" alpha:0.7].CGColor;
    passBg.backgroundColor = [UIColor dc_colorWithHexString:@"#FFFFFF" alpha:0.4];
    passBg.layer.cornerRadius = 23;
    passBg.layer.masksToBounds = YES;
    [self.view addSubview:passBg];
    [passBg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(30);
        make.right.offset(-30);
        make.height.mas_equalTo(46);
        make.top.mas_equalTo(mailBg.mas_bottom).offset(25);
    }];
    
    UIImageView *passLogo = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ai_log_pass"]];
    [passBg addSubview:passLogo];
    [passLogo mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(17);
        make.top.offset(12);
        make.height.width.mas_equalTo(22);
    }];
    
    self.passField = [[UITextField alloc] init];
    self.passField.font = PFRFont(16);
    self.passField.textColor = [UIColor colorWithHexString:@"#000000"];
    NSString *placeHodle1 = @"填写验证码";
    NSMutableAttributedString *attributedString1 = [[NSMutableAttributedString alloc] initWithString:placeHodle1];
    [attributedString1 addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHexString:@"#AEBFCC"] range:NSMakeRange(0, placeHodle1.length)];
    [attributedString1 addAttribute:NSFontAttributeName value:PFRFont(16) range:NSMakeRange(0, placeHodle1.length)];
    self.passField.attributedPlaceholder = attributedString1;
    [passBg addSubview:self.passField];
    [self.passField addBlockForControlEvents:UIControlEventEditingChanged block:^(UITextField *sender) {
        [weakSelf judgeBtnState];
    }];
    
    [self.passField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(51);
        make.top.bottom.offset(0);
        make.right.offset(-90);
    }];
    
    self.sendLab = [[UILabel alloc] init];
    self.sendLab.textColor = [UIColor colorWithHexString:@"#1D8EFF"];
    self.sendLab.font = PFRFont(14);
    self.sendLab.userInteractionEnabled = YES;
    [passBg addSubview:self.sendLab];
    self.sendLab.text = @"获取验证码";
    [self.sendLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-15);
        make.centerY.mas_equalTo(passBg);
    }];
    [self.sendLab addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
        [weakSelf sendVertic];
    }]];
   
    self.choseBtn = [[ExpandButton alloc]init];
    [self.choseBtn setImage:[UIImage imageNamed:@"椭圆 4"] forState:UIControlStateNormal];
    [self.choseBtn setImage:[UIImage imageNamed:@"组 182"] forState:UIControlStateSelected];
    [self.choseBtn addTarget:self action:@selector(choseclick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.choseBtn];
    
    self.choseLab = [[YYLabel alloc] init];
    self.choseLab.font = PFRFont(12);
    self.choseLab.textColor = [UIColor colorWithHexString:@"#999999"];
    self.choseLab.numberOfLines = 0;
    [self.view addSubview:self.choseLab];
    [self.choseLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(55);
        make.right.offset(-34);
        make.top.mas_equalTo(passBg.mas_bottom).offset(30);
        make.height.mas_equalTo(40);
    }];
    
    [self.choseBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.width.mas_equalTo(16);
        make.right.mas_equalTo(self.choseLab.mas_left).offset(-5);
        make.centerY.mas_equalTo(self.choseLab);
    }];
    
    NSString *str = @"我已阅读并同意《用户协议》和《隐私政策》并同意授权本应用获取谷歌账号信息";
    NSMutableAttributedString *titleText = [[NSMutableAttributedString alloc] initWithString:str];
    NSRange range1 = [str rangeOfString:@"《用户协议》"];
    NSRange range2 = [str rangeOfString:@"《隐私政策》"];


    [titleText setTextHighlightRange:range1 color:[UIColor colorWithHexString:@"#1D8EFF"] backgroundColor:nil tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
   
    }];
    [titleText setTextHighlightRange:range2 color:[UIColor colorWithHexString:@"#1D8EFF"] backgroundColor:nil tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
     
    }];

    
    YYTextContainer *container = [YYTextContainer containerWithSize:CGSizeMake(kScreenW-89, MAXFLOAT)];;
    YYTextLayout *titleTextLayout = [YYTextLayout layoutWithContainer:container text:titleText];
    self.choseLab.textLayout = titleTextLayout;
    
    self.loginLab = [[UILabel alloc] init];
    self.loginLab.textAlignment = NSTextAlignmentCenter;
    self.loginLab.text = @"立即登录";
    self.loginLab.textColor = [UIColor whiteColor];
    self.loginLab.font = PFRFontSemibold(18);
    self.loginLab.backgroundColor = [UIColor dc_colorWithHexString:@"#1D8EFF" alpha:0.7];
    [self.view addSubview:self.loginLab];
    self.loginLab.layer.cornerRadius = 26;
    self.loginLab.layer.masksToBounds = YES;
    self.loginLab.userInteractionEnabled = YES;
    [self.loginLab addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
        [weakSelf clickLogin];
    }]];
    [self.loginLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(52);
        make.left.offset(46);
        make.right.offset(-46);
        make.top.mas_equalTo(self.choseLab.mas_bottom).offset(45);
    }];
    
    UILabel *noticeLab = [[UILabel alloc] init];
    noticeLab.textColor = [UIColor colorWithHexString:@"#999999"];
    noticeLab.font = PFRFont(12);
    noticeLab.numberOfLines = 0;
    [self.view addSubview:noticeLab];
    noticeLab.textAlignment = NSTextAlignmentCenter;
    noticeLab.text = @"未注册邮箱验证后即可完成注册";
    [noticeLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.width.mas_equalTo(200);
        make.top.mas_equalTo(self.loginLab.mas_bottom).offset(10);
    }];
}

//发送验证码
- (void)sendVertic {
    if (self.emailField.text.length == 0) {
        return;
    }
//    [self cutDown];
    [[DCHttpClient shareClient] requestWithPath:@"api/user/sendEmail" params:@{@"":@""} httpMethod:DCHttpRequestPost sucess:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSDictionary * dict = [responseObject mj_JSONObject];
        
    } failture:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        
    }];
}

#pragma mark  -----勾选协议------
- (void)choseclick:(UIButton*)btn{
    btn.selected = ! btn.selected;
    [self judgeBtnState];
}

//登录
- (void)clickLogin {
//    WEAKSELF;
//    [[DCHttpClient shareClient] requestWithPath:@"api/login/emailAccountLogin" params:@{@"account":@"1753239161@qq.com",@"email_code":@"1234",@"terminal":@"5"} httpMethod:DCHttpRequestPost sucess:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
//        NSDictionary * dict = [responseObject mj_JSONObject];
//        if([dict[@"code"] intValue]==1){
//            [DCObjectManager dc_saveUserData:[NSString stringWithFormat:@"%@",dict[@"data"][@"token"]] forKey:DC_Token_Key];
//            
//            UIWindow *window = [self getKeyWindow];
//            window.rootViewController = [[DCNavigationController alloc] initWithRootViewController:[[YNSHomeController alloc] init]];
//            [window makeKeyAndVisible];
//        }
//        else {
//            [SVProgressHUD showWithStatus:dict[@"msg"]];
//        }
//    } failture:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
//        
//    }];
    DCMyProductionViewController *proVc = [[DCMyProductionViewController alloc] init];
    [self.navigationController pushViewController:proVc animated:YES];
}

- (UIWindow *)getKeyWindow {
    
    UIWindow *keyWindow;
    if (@available(iOS 13.0, *)) {
        
        for (UIWindowScene* windowScene in [UIApplication sharedApplication].connectedScenes) {
            if (windowScene.activationState == UISceneActivationStateForegroundActive) {
                
                keyWindow = windowScene.windows.firstObject;
                break;
            }
        }
    }
    return keyWindow;
}

- (void)judgeBtnState {
    
    if (self.emailField.text.length >0 && self.passField.text.length >0&&self.choseBtn.isSelected) {
        self.loginLab.backgroundColor = [UIColor colorWithHexString:@"#1D8EFF"];
        self.loginLab.userInteractionEnabled = YES;
    } else {
        self.loginLab.backgroundColor = [UIColor dc_colorWithHexString:@"#1D8EFF" alpha:0.7];
        self.loginLab.userInteractionEnabled = NO;
    }
}

- (void)cutDown {
    
//    AIChargeListController *listVc = [[AIChargeListController alloc] init];
//    [self.navigationController pushViewController:listVc animated:YES];
    //开始倒计时
    __block NSInteger time = 59; //倒计时时间
    self.sendLab.userInteractionEnabled = NO;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
       if(time <= 0){ //倒计时结束，关闭
           dispatch_source_cancel(self->_timer);
           dispatch_async(dispatch_get_main_queue(), ^{
               self.sendLab.userInteractionEnabled = YES;
               self.sendLab.text = @"获取验证码";
           });
       }else{
           int seconds = time % 60;
           dispatch_async(dispatch_get_main_queue(), ^{
               self.sendLab.text = [NSString stringWithFormat:@"%.2ds", seconds];
           });
           time--;
       }
    });
    dispatch_resume(_timer);
}

@end
